package com.taiyuan.tongcheng.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.StringUtils;
import org.kymjs.kjframe.utils.SystemTool;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.taiyuan.tongcheng.adapter.CarKindAdapter;
import com.taiyuan.tongcheng.adapter.PayKindAdapter;
import com.taiyuan.tongcheng.application.TCBroadcastAction;
import com.taiyuan.tongcheng.bean.BjExtraServiceInfo;
import com.taiyuan.tongcheng.bean.MovingOrderSimple;
import com.taiyuan.tongcheng.bean.MovingPrice;
import com.taiyuan.tongcheng.http.HttpParamUtil;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.util.ACache;
import com.tytc56.user.R;

/**
 * 
* @Description 搬家订单界面
* @author wzq
* @date 2015-9-18 上午10:02:02
* @update (date)
* @version V1.0
 */
public class MovingOrderMakeActivity extends BaseActivity{
	//==widget
	@BindView(id=R.id.btn_make_order,click=true)
	private Button  orderBtn;
	//基本信息
	@BindView(id=R.id.tv_moving_start)
	private TextView  startTv;
	@BindView(id=R.id.tv_moving_end)
	private TextView  endTv;
	@BindView(id=R.id.tv_moving_time)
	private TextView  timeTv;
	@BindView(id=R.id.tv_moving_pay_style)
	private TextView  payTv;
	@BindView(id=R.id.tv_moving_note)
	private TextView  noteTv;
	@BindView(id=R.id.tv_moving_car_style)
	private TextView  carStyle;
	@BindView(id=R.id.tv_moving_tel)
	private TextView  telTv;
	
	//价格
	@BindView(id =R.id.tv_moving_all_price)
	private TextView movingAllPriceTv;
	@BindView(id =R.id.tv_price_moving)
	private TextView movingPriceTv;
	@BindView(id =R.id.tv_price_moving_service)
	private TextView servicePriceTv;
	//搬家数量
	@BindView(id=R.id.tv_furniture_num)
	private TextView furnitureNumTv;
	@BindView(id=R.id.tv_air_num)
	private TextView airNumTv;
	@BindView(id=R.id.tv_valuables_num)
	private TextView valuesNumTv;
	@BindView(id=R.id.tv_meirong_num)
	private TextView meirongNumTV;
	//价格详情
	@BindView(id=R.id.ll_btn_detail_extral,click=true)
	private LinearLayout  detailBtn;
	@BindView(id=R.id.ll_moving_price_detail)
	private LinearLayout  priceDetailLayout;
	@BindView(id=R.id.tv_price_start)
	private TextView startPrice;
	@BindView(id=R.id.tv_price_km)
	private TextView kmPrice;
	@BindView(id=R.id.tv_price_czservice)
	private TextView servicePrice;
	@BindView(id=R.id.tv_price_night)
	private TextView nightPrice;
	@BindView(id=R.id.tv_price_floor)
	private TextView floorPrice;
	@BindView(id=R.id.tv_coupon)
    private TextView couponPrice;	
	//价格详情
	@BindView(id=R.id.rl_moving_serive_detail,click=true)//详情页打开
	private RelativeLayout movingServiceDetailRl;
	@BindView(id=R.id.img_service_price_detail,click=true)
	private ImageView rightArrowImg;
	@BindView(id=R.id.rl_moving_serive_close,click=true)//详情页关闭
	private RelativeLayout movingServiceCloseRL;
	@BindView(id=R.id.tv_service_price1)
	private TextView  priceServiceTv1;
	@BindView(id=R.id.tv_service_price2)
	private TextView  priceServiceTv2;
	@BindView(id=R.id.tv_service_price3)
	private TextView  priceServiceTv3;
	@BindView(id=R.id.tv_service_price4)
	private TextView  priceServiceTv4;
	@BindView(id=R.id.ll_service_price_detail)
	private LinearLayout  serviceDetailLayout;
	@BindView(id=R.id.top_ll)
	private ScrollView  contentScrollView;
	@BindView(id=R.id.rl_service_1)
	private RelativeLayout service1RL;
	@BindView(id=R.id.rl_service_2)
	private RelativeLayout service2RL;
	@BindView(id=R.id.rl_service_3)
	private RelativeLayout service3RL;
	@BindView(id=R.id.rl_service_4)
	private RelativeLayout service4RL;
	//==data
	private MovingOrderSimple  movingOrder=new MovingOrderSimple();
	private MovingPrice  movingPrice=new MovingPrice();
	private List<BjExtraServiceInfo> serviceList =new ArrayList<BjExtraServiceInfo>();
	private List<String> serviceListString =new ArrayList<String>();
    private double discount=9.0;
	//==
	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
		}
		
	};
	@Override
    public void setRootView() {
    	super.setRootView();
    	setContentView(R.layout.activity_movingodrer_make);
    }
    
    @Override
    public void initWidget() {
    	super.initWidget();
    	initView();
    	discount=Double.parseDouble(spUtil.getBjDiscount());
    	
    	movingOrder=(MovingOrderSimple)ACache.get(getApplicationContext()).getAsObject(MovingActivity.TAG_MOVING_ORDER);
    	movingPrice=(MovingPrice)ACache.get(getApplicationContext()).getAsObject(MovingActivity.TAG_MOVING_ORDER_PRICE);
    	KJLoger.debug(movingOrder.toString());
    	
    	topTv.setText(R.string.top_title_confirm);
    	rightTv.setVisibility(View.GONE);
    	//价格
    	movingAllPriceTv.setText("￥"+(movingPrice.getStartPrice()+movingPrice.getTotalFloorPrice()+movingPrice.getExtraServicePrice()+movingPrice.getLiChengPrice()+movingPrice.getNightServicePrice()-movingOrder.getCouponPrice()));
    	movingPriceTv.setText(movingPrice.getStartPrice()+movingPrice.getLiChengPrice()+"");
    	servicePriceTv.setText(movingPrice.getExtraServicePrice()+movingPrice.getNightServicePrice()+movingPrice.getTotalFloorPrice()+"");
    	serviceList=movingOrder.getExtraServiceInfoList();
    	furnitureNumTv.setText("X"+serviceList.get(0).getNum());
    	valuesNumTv.setText("X"+serviceList.get(1).getNum());
    	airNumTv.setText("X"+serviceList.get(2).getNum());
    	meirongNumTV.setText("X"+serviceList.get(3).getNum());
    	//价格详情
    	startPrice.setText("￥"+movingPrice.getStartPrice());
    	kmPrice.setText("￥"+movingPrice.getLiChengPrice());
    	nightPrice.setText("￥"+movingPrice.getNightServicePrice());
    	floorPrice.setText("￥"+movingPrice.getTotalFloorPrice());
    	servicePrice.setText("￥"+movingPrice.getExtraServicePrice());
    	couponPrice.setText("￥-"+movingOrder.getCouponPrice());
    	//具体服务项
    	if(movingPrice.getExtraServicePrice()>0){
    		
    	}else{
    		rightArrowImg.setVisibility(View.GONE);
    	}
    	
    	serviceListString=JSON.parseArray(movingPrice.getServiceListInfo(), String.class);
    	//=========增加服务详情20151108=================
    	for (String serviceString: serviceListString) {
			BjExtraServiceInfo  serviceInfo =JSON.parseObject(serviceString, BjExtraServiceInfo.class);
//			KJLoger.debug(serviceInfo.toString());
			switch (serviceInfo.getBjExtraServiceId()) {
			case MovingListActivity.FURNITURE_KIND:
				service1RL.setVisibility(View.VISIBLE);
				priceServiceTv1.setText(getServicePriceDetailString(serviceInfo));
				break;
			case MovingListActivity.KONGTIAO_KIND:
				KJLoger.debug(serviceInfo.getName()+"："+serviceInfo.getNum()+"单价"+serviceInfo.getPrice());
				service2RL.setVisibility(View.VISIBLE);
				priceServiceTv2.setText(getServicePriceDetailString(serviceInfo));
				break;
			case MovingListActivity.PRECIOUS_KIND:
				service3RL.setVisibility(View.VISIBLE);
				priceServiceTv3.setText(getServicePriceDetailString(serviceInfo));
				KJLoger.debug(serviceInfo.getName()+"："+serviceInfo.getNum()+"单价"+serviceInfo.getPrice());
				break;
			case MovingListActivity.MEIRONG_KIND:
				service4RL.setVisibility(View.VISIBLE);
				priceServiceTv4.setText(getServicePriceDetailString(serviceInfo));
				KJLoger.debug(serviceInfo.getName()+"："+serviceInfo.getNum()+"单价"+serviceInfo.getPrice());
				break;
			default:
				break;
			}
    	}
    	
    	//基本信息
    	startTv.setText(movingOrder.getStartPlace());
    	endTv.setText(movingOrder.getEndPlace());
    	timeTv.setText(movingOrder.getServiceDate());
    	payTv.setText(PayKindAdapter.payName[movingOrder.getPayTypeId()-1]);
    	carStyle.setText(CarKindAdapter.carName[movingOrder.getTruckTypeId()-1]);
    	telTv.setText(movingOrder.getReceiverMobile());
    	
    	if(StringUtils.isEmpty(movingOrder.getNote())){
    		noteTv.setText("无");
    	}else{
    		noteTv.setText(movingOrder.getNote());
    	}

    }
    
    private String  getServicePriceDetailString(BjExtraServiceInfo  serviceInfo) {
    	if(serviceInfo.getNum()>0){
    		return  serviceInfo.getName()+"："+serviceInfo.getNum()+"*"+serviceInfo.getPrice()+"(单价) ="+serviceInfo.getNum()*serviceInfo.getPrice();
    	}else{
    		return  serviceInfo.getName()+"："+serviceInfo.getNum()+"*"+serviceInfo.getPrice()+"(单价) = 0.0";
    	}
	}
    @Override
    public void widgetClick(View v) {
    	super.widgetClick(v);
    	switch (v.getId()) {
		case R.id.btn_make_order:
			if(check()){
				TcLoaddingDialog.show();
				makeMovingOrder(movingOrder, movingPrice);
			}
			break;
		case R.id.ll_btn_detail_extral:
			if(priceDetailLayout.getVisibility()==View.GONE){
				priceDetailLayout.setVisibility(View.VISIBLE);
			}else{
				priceDetailLayout.setVisibility(View.GONE);
			}
			break;
		case R.id.rl_moving_serive_detail:
			if(movingPrice.getExtraServicePrice()>0){
				serviceDetailLayout.setVisibility(View.VISIBLE);
				rightArrowImg.setVisibility(View.GONE);
//				handler.post(new Runnable() {
//				    @Override
//				    public void run() {
//				    	contentScrollView.fullScroll(ScrollView.FOCUS_DOWN);
//				    }
//				});
			}
			break;
		case R.id.rl_moving_serive_close:
			serviceDetailLayout.setVisibility(View.GONE);
			rightArrowImg.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}
    }
    
    
    /**
     * 
    * @Description: 判断输入条件
    * @return
    * @return boolean
    * @throws
    * @autour wzq
    * @date 2015-9-18 上午10:29:17
    * @update (date)
     */
    private boolean check() {
    	if(SystemTool.checkNet(getApplicationContext())){
    		return true;
    	}else{
    		return false;
    	}
	}

	/**
     * 
    * @Description: 下搬家单子
    * @param movingOrder
    * @param movingPrice
    * @return void
    * @throws
    * @autour wzq
    * @date 2015-9-18 上午10:23:37
    * @update (date)
     */
    private void makeMovingOrder(MovingOrderSimple movingOrder,MovingPrice movingPrice) {
    	HttpConfig config =new HttpConfig();
    	config.cacheTime=0;
        KJHttp  kjHttp =new KJHttp(config);
        HttpParams  params =HttpParamUtil.getMakeMovingOrder(getApplicationContext(), movingOrder, movingPrice);
         KJLoger.debug(TcWebservice.WEBSERVER_IP+TcWebservice.API.MOVING_MAKE_ORDER+params.getUrlParams().toString());
        kjHttp.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.MOVING_MAKE_ORDER, params, new HttpCallBack() {

			@Override
			public void onFailure(int errorNo, String strMsg) {
				super.onFailure(errorNo, strMsg);
			}

			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				try {
					String resp = URLDecoder.decode(t, "UTF-8");
					KJLoger.debug(resp);
					
					WebData webData = TcJsParser.getWedataData(resp);
					if (webData.getStatus() == 1) {
						if(	TcLoaddingDialog!=null&&TcLoaddingDialog.isShowing()){
							TcLoaddingDialog.cancel();
						}
						showinformDialog("提示", getOrderSuccessShowInfo(discount), new View.OnClickListener() {
							
							@Override
							public void onClick(View v) {
								MovingOrderMakeActivity.this.finish();
								tcInformDialog.dismiss();
								sendBroadcast(new Intent(TCBroadcastAction.SUCCESS_MAKE_ORDER));
								Bundle bundle=new Bundle();
								bundle.putInt(OrderActivity.TAG_FROM, OrderActivity.TAG_FROM_MOVING);
								startActivity(OrderActivity.class, bundle);
							}
						}, new View.OnClickListener() {
							
							@Override
							public void onClick(View v) {
								MovingOrderMakeActivity.this.finish();
								tcInformDialog.dismiss();
								sendBroadcast(new Intent(TCBroadcastAction.SUCCESS_MAKE_ORDER));
							}
						});
					}else if(webData.getStatus()==-1){
						showErroCustomToast(webData.getMsg());
						GotoLogin();
					}else {
						showCustomToast(webData.getMsg());
					}
					
					
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
                    
        });
    }
    
    /**
     * 
     * @param dicount
     * @return 获取折扣显示信息
     */
    private String getOrderSuccessShowInfo(double discount) {
       if(movingOrder.getPayTypeId()==1&&discount>0&&discount<10){
    	   return "您的搬家订单已经提交！稍后会有客服与您联系，离开此界面您可以在我的订单查看订单信息，如有疑问请拨打热线4001565556，支付定金，立享折扣额度值"+discount+"折优惠";
       }else{
    	   return "您的搬家订单已经提交！稍后会有客服与您联系，离开此界面您可以在我的订单查看订单信息，如有疑问请拨打热线4001565556";
       }
	}
    
    
}
